/**
 * @author scylla
 * @version V1.0
 * @Project echo-java-base
 * @Title 尝试获取锁 示例
 * @Description *
 * @Package concurrent.mthread.bf
 * @Since 2021/8/13 9:46 上午
 */
package concurrent.mthread.bf;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AttemptLocking {

    private Lock lock = new ReentrantLock();

    public void untimed() {
        boolean captured = lock.tryLock();
        try {
            //输出取锁日志
            System.out.println("tryLock(): " + captured);
        } finally {
            //获得锁后立即解锁
            if (captured) lock.unlock();
        }
    }

    public void timed() {
        boolean captured = false;
        try {
            //取锁 2s 后取不到抛异常
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
            //2s 内 取到锁则输出日志。
            System.out.println("tryLock(2, TimeUnit.SECONDS) :" + captured);
        } finally {
            //获得锁后立即解锁
            if (captured) lock.unlock();
        }
    }


    public static void main(String[] args) {
        final AttemptLocking al = new AttemptLocking();
        al.untimed();
        al.timed();

        //新建线程 只做获取锁动作，并不释放
        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                al.lock.lock();
                System.out.println("acquired");
            }
        }.start();

        //让出时间片
        Thread.yield();
        al.untimed();
        al.timed();
    }

}
